package grpc_server

import (
	"context"

	"code.byted.org/bytertc/whiteboard_server/biz/api"
	"code.byted.org/bytertc/whiteboard_server/biz/api/pb/wb_pb"
	"code.byted.org/bytertc/whiteboard_server/biz/pkg/util"
	"code.byted.org/bytertc/whiteboard_server/biz/rts"
	"code.byted.org/gopkg/logs/v2/log"
)

type Handler struct {
	rtsAdapter rts.Adapter
	rtsManager rts.Manager
}

func NewHandler(rtsAdapter rts.Adapter, rtsManager rts.Manager) *Handler {
	return &Handler{
		rtsAdapter: rtsAdapter,
		rtsManager: rtsManager,
	}
}

func (h *Handler) RtsMsg(stream wb_pb.Whiteboard_RtsMsgServer) error {
	for {
		ctx := util.EnsureID(context.Background())
		request, err := stream.Recv()
		if err != nil {
			log.V1.CtxError(ctx, "recv rts_msg from rts proxy error:%v", err)
			return err
		}
		if request != nil {
			log.V1.CtxInfo(ctx, "recv rts_msg,app_id:%s,user_id:%s,data:%v", request.GetAppId(), request.GetUserId(), string(request.GetData()))
			go h.rtsAdapter.HandleMessage(ctx, &api.AuthTokenKeyParams{}, string(request.GetData()), rts.Ext{Source: rts.SourceRtsSDK})
		}
	}
}
func (h *Handler) Heartbeat(stream wb_pb.Whiteboard_HeartbeatServer) error {
	for {
		ctx := util.EnsureID(context.Background())
		request, err := stream.Recv()
		if err != nil {
			log.V1.CtxError(ctx, "recv heartbeat from rts proxy error:%v", err)
			return err
		}
		if request != nil {
			log.V1.CtxInfo(ctx, "recv heartbeat,app_id:%s,rooms:%+v", request.GetAppId(), request.GetRooms())
			go h.rtsManager.RtsHeartbeat(ctx, request.GetAppId(), request.GetRooms())
		}
	}
}
func (h *Handler) Event(stream wb_pb.Whiteboard_EventServer) error {
	for {
		ctx := util.EnsureID(context.Background())
		request, err := stream.Recv()
		if err != nil {
			log.V1.CtxError(ctx, "recv event from rts proxy error:%v", err)
			return err
		}
		if request != nil {
			log.V1.CtxInfo(ctx, "recv event,event_type:%v,app_id:%s,room_id:%s,content:%s", request.GetType(), request.GetAppId(), request.GetRoomId(), request.GetContent())
			go h.rtsManager.RtsEvent(ctx, request.GetType(), request.GetAppId(), request.GetRoomId(), request.GetContent())
		}
	}
}
func (h *Handler) Log(stream wb_pb.Whiteboard_LogServer) error {
	for {
		ctx := util.EnsureID(context.Background())
		request, err := stream.Recv()
		if err != nil {
			log.V1.CtxError(ctx, "recv log from rts proxy error:%v", err)
			return err
		}
		if request != nil {
			switch request.GetType() {
			case wb_pb.LogType_kLogError:
				log.V1.CtxError(ctx, "recv log,app_id:%s,content:%s", request.GetAppId(), request.GetContent())
			case wb_pb.LogType_kLogWarn:
				log.V1.CtxWarn(ctx, "recv log,app_id:%s,content:%s", request.GetAppId(), request.GetContent())
			default:
				log.V1.CtxInfo(ctx, "recv log,app_id:%s,content:%s", request.GetAppId(), request.GetContent())
			}
		}
	}
}
